package com.lr.falsework.common.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.time.LocalDateTime;
import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;
import com.lr.app.application.MySession;
import com.lr.app.application.MySessionContext;
import com.lr.app.entity.SysUser;
import com.ws.commons.interfac.Result;
import com.ws.commons.tool.StrTool;

import jxl.read.biff.BiffException;

/**
 * 
 * @author ljl·尘无尘
 * @date Aug 15, 2018
 */
public class WebContainerTool{
	public static final String SESSION_USER="SESSION_USER";
	public static final String SESSION_KEY="XToken";
	public static final String REQUEST_TREAD_DATE="REQUEST_TREAD_DATE";
	public static final String REQUEST_TREAD_LCDATE="REQUEST_TREAD_LCDATE";
	
	

	
	public static HttpServletRequest getRequest() {
		return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest();
	}
	
	public static LocalDateTime getOfReqThreadLCDate() {
		HttpServletRequest req=getRequest();
		LocalDateTime localDateTime=(LocalDateTime)req.getAttribute(REQUEST_TREAD_DATE);
		if(localDateTime==null) {
			localDateTime=LocalDateTime.now();
			req.setAttribute(REQUEST_TREAD_DATE, localDateTime);
		}
		return localDateTime;
	}
	
	public static Date getOfReqThreadDate() {
		HttpServletRequest req=getRequest();
		Date date=(Date)req.getAttribute(REQUEST_TREAD_LCDATE);
		if(date==null) {
			date=new Date();
			req.setAttribute(REQUEST_TREAD_LCDATE, date);
		}
		return date;
	}
	
	
	
	public static String  getToken() {
		HttpServletRequest reques=WebContainerTool.getRequest();
		String token=reques.getHeader(SESSION_KEY);
		if(StrTool.isEmpty(token)) {
			token=reques.getParameter(SESSION_KEY);
		}
		return token;
	}

	public static MySession getSession() {
		return MySessionContext.getSession(getToken());
	}
	public static SysUser getCurrentUser(MySession session) {
		return (SysUser)session.getLoginUser();
	}
	public static SysUser getCurrentUser() {
		MySession mySession=getSession();
		if(mySession==null) {
			return null;
		} 
		return (SysUser)mySession.getLoginUser();
	}
	public static void setCurrentUser(SysUser user) {
		 getSession().updateLoginUser(user);
	}
	public static void setCurrentUser(MySession session,SysUser user) {
		session.updateLoginUser(user);
	}
	public static HttpServletResponse getResponse() {
		return ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getResponse();
	}


	   public static void responseFile(File file) throws BiffException, IOException {
		   HttpServletResponse response= WebContainerTool.getResponse();
		   response.reset();
			response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
			response.setHeader("Content-disposition", "attachment; filename=" +file.getName());
	    	OutputStream out=response.getOutputStream();
			InputStream is = new FileInputStream(file);      //创建一个文件流，读入Excel文件
			byte[] bt=new byte[1024];
			int n;
			while((n=is.read(bt,0,bt.length))!=-1){
				out.write(bt,0,n);
			}
	    	out.flush();
	    	is.close();
	    	out.close();
	    }
	   
	   public static void responseResult(Result result) {
		   HttpServletResponse response= WebContainerTool.getResponse();
               PrintWriter writer = null;
               OutputStreamWriter osw = null;
               response.setHeader("Content-type", "text/html;charset=UTF-8");
               try {
            	   response.setCharacterEncoding("UTF-8");
                   osw = new OutputStreamWriter(response.getOutputStream(),"UTF-8");
                   writer = new PrintWriter(osw, true);    
                   String jsonStr = JSON.toJSONString(result);
                   writer.write(jsonStr);   
                   writer.flush();
                   writer.close();  
                   osw.close();
               }catch (UnsupportedEncodingException e) {
                   e.printStackTrace();
               } catch (IOException e) {
            	   e.printStackTrace();
               } finally {
                   if (null != writer) {
                       writer.close();
                   }
                   if (null != osw) {
                       try {
						osw.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
                   }
               }

	   }
	   
	   
	   
	   public static void responseFile(InputStream inputStream,String fileName) throws BiffException, IOException {
		   HttpServletResponse response= WebContainerTool.getResponse();
		   response.reset();
		   response.setContentType("application/vnd.ms-excel"); // 改成输出excel文件
		   response.setHeader("Content-disposition", "attachment; filename=" +fileName);
		   OutputStream out=response.getOutputStream();
		   byte[] bt=new byte[1024];
		   int n;
		   while((n=inputStream.read(bt,0,bt.length))!=-1){
			   out.write(bt,0,n);
		   }
		   out.flush();
		   inputStream.close();
		   out.close();
	   }
	   
	   

}
  